package com.jiuzhe.commercial.ui.house;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.zhouwei.library.CustomPopWindow;
import com.jiangyy.easydialog.SingleChoiceDialog;
import com.jiuzhe.commercial.R;
import com.jiuzhe.commercial.adapter.HouseListAdapter;
import com.jiuzhe.commercial.base.BaseActivity;
import com.jiuzhe.commercial.bean.CalendarBean;
import com.jiuzhe.commercial.bean.HouseListBean;
import com.jiuzhe.commercial.constant.Constants;
import com.jiuzhe.commercial.http.CallBack;
import com.jiuzhe.commercial.http.HttpClient;
import com.jiuzhe.commercial.utils.RxBus;
import com.jiuzhe.commercial.utils.SPUtil;
import com.jiuzhe.commercial.utils.UIUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by huanghao on 2018/4/27.
 */

public class HouseListActivity extends BaseActivity {
    @BindView(R.id.listview)
    RecyclerView recyclerView;
    @BindView(R.id.cb_all)
    CheckBox cbAll;
    @BindView(R.id.iv_not)
    ImageView ivNot;


    private List<HouseListBean> list = new ArrayList<>();
    private List<String> mNewDatas = new ArrayList<>();
    private HouseListAdapter mHouseAdapter;
    private CustomPopWindow mCustomPopWindow;

    private boolean flag = true;        //全选或全取消

    MyHandler handler = new MyHandler(this);
    private ImageView ibChoice;
    private TextView tvOnline;
    private static final int H_CODE_UPDATE = 2;
    private HouseListBean houseListBean;
    private HashMap<Integer, Boolean> map;
    private AlertDialog alertDialog;
    Subscription mSubscription;
    private String mPrice;
    private String mStartDate;
    private String mEndDate;


    public class MyHandler extends Handler {
        private WeakReference<HouseListActivity> reference;

        public MyHandler(HouseListActivity activity) {
            reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    //所有列表中的商品全部被选中，让全选按钮也被选中
                    //flag记录是否全被选中
                    flag = !(Boolean) msg.obj;
                    cbAll.setChecked((Boolean) msg.obj);
                    break;
                case H_CODE_UPDATE:
                    DiffUtil.DiffResult diffResult = (DiffUtil.DiffResult) msg.obj;
                    diffResult.dispatchUpdatesTo(mHouseAdapter);
                    //所有列表中的商品全部被选中，让全选按钮也被选中
                    //flag记录是否全被选中
                    mHouseAdapter.setDatas(list);
                    break;
                default:
                    break;
            }
        }
    }


    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.house_list_activity);
        setTitle("房源");
    }

    @Override
    protected void loadData() {
        dialog.show();
        list.clear();
        HashMap<String, String> map = new HashMap<>();
        map.put("merchantId",SPUtil.getString(HouseListActivity.this, Constants.MERCHANTID));
        String token = SPUtil.getString(HouseListActivity.this, Constants.TOKEN);
        String id = SPUtil.getString(HouseListActivity.this, Constants.ID);
        String autoSignStr = Constants.SKUDETAILS.substring(Constants.SKUDETAILS.lastIndexOf("0/") + 1) + "?token=";
        String signStr = UIUtils.Md5(autoSignStr + token);
        map.put("token", id);
        map.put("sign", signStr);
        HttpClient.post(this, Constants.SKUDETAILS, map, new CallBack<List<HouseListBean>>() {
            @Override
            public void onSuccess(List<HouseListBean> result) {
                dialog.dismiss();
                if (result.size() > 0) {
                    list.addAll(result);
                    recyclerView.setLayoutManager(new LinearLayoutManager(HouseListActivity.this));
                    //设置Item增加、移除动画
                    recyclerView.setItemAnimator(new DefaultItemAnimator());
                    mHouseAdapter = new HouseListAdapter(list, handler);
                    recyclerView.setAdapter(mHouseAdapter);
                    mHouseAdapter.notifyDataSetChanged();
                } else {
                    ivNot.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailure(int errorType, String message) {
                super.onFailure(errorType, message);
                dialog.dismiss();
            }
        });
    }


    @OnClick({R.id.cb_all, R.id.tv_edit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cb_all:
                selectedAll();   //全选
                break;
            case R.id.tv_edit:   //编辑
                mNewDatas.clear();
                int totalNum = 0;
                for (int i = 0; i < list.size(); i++) {
                    houseListBean = list.get(i);
                    if (houseListBean.isChoosed()) {
                        totalNum += 1;
                        mNewDatas.add(houseListBean.getSkuId());
                    }
                }
                if (totalNum > 0) {
                    showEditState();
                  //  showEditState2();
                } else {
                    UIUtils.showToastSafe("请选择勾选编辑按钮");
                }
                break;
        }
    }

    private void showEditState2() {
        new SingleChoiceDialog.Builder(this).setTitle("提示")
                .addList(new String[]{"已上线", "脏房"})
                .setOnItemClickListener(new SingleChoiceDialog.OnItemClickListener() {
                    @Override
                    public void OnItemClick(String title, int position) {

                        HashMap<String, String> map2 = new HashMap<>();

                        for (int i = 0; i < list.size(); i++) {
                            houseListBean = list.get(i);
                            if (houseListBean.isChoosed()) {
                                map2.put("skuId",houseListBean.getSkuId());
                            }
                        }

                        String token = SPUtil.getString(HouseListActivity.this, Constants.TOKEN);
                        String id = SPUtil.getString(HouseListActivity.this, Constants.ID);
                        String autoSignStr = Constants.DURTYUPDATING.substring(Constants.DURTYUPDATING.lastIndexOf("0/") + 1) + "?token=";
                        String signStr = UIUtils.Md5(autoSignStr + token);
                        String url = Constants.DURTYUPDATING + "?token=" + id + "&&sign=" + signStr;
                        HttpClient.post(this, url, map2, new CallBack<String>() {
                            @Override
                            public void onSuccess(String result) {
                                loadData();
                            }
                        });
                    }
                }).show();
    }


    private TextView tvSalePrice;
    private TextView etRoomPrice;
    private TextView etRoomCash;

    /**
     * 编辑内容
     */
    private void showEditState() {
        alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_house_state);
        window.setGravity(Gravity.CENTER);
        window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = this.getResources().getDisplayMetrics().widthPixels;
        window.setAttributes(lp);
        ibChoice = (ImageView) alertDialog.findViewById(R.id.ib_choice);
        ImageButton ibDate = (ImageButton) alertDialog.findViewById(R.id.ib_date);
        tvOnline = (TextView) alertDialog.findViewById(R.id.tv_online);
        tvSalePrice = (TextView) alertDialog.findViewById(R.id.tv_sale_price);
        etRoomPrice = (TextView) alertDialog.findViewById(R.id.et_room_price);
        etRoomCash = (TextView) alertDialog.findViewById(R.id.et_room_cash);
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCustomPopWindow != null) {
                    mCustomPopWindow.dissmiss();
                }
                switch (v.getId()) {
                    case R.id.btn_cancel:
                        alertDialog.dismiss();
                        break;
                    case R.id.ib_date:
                        etRoomCash.setInputType(InputType.TYPE_NULL); // 关闭软键盘
                        UIUtils.startActivity(CalendarActivity.class);
                        break;
                    case R.id.ib_choice:
                      //  showPopMenu();
                        break;
                    case R.id.bt_ok:
                        String roomCash = etRoomCash.getText().toString().trim();
                        String roomPrice = etRoomPrice.getText().toString().trim();
                        String salePrice = tvSalePrice.getText().toString().trim();
                        if (TextUtils.isEmpty(roomPrice)) {
                            UIUtils.showToastSafe("请填写房价");
                            return;
                        }
                        if (TextUtils.isEmpty(roomCash)) {
                            UIUtils.showToastSafe("请填写压金");
                            return;
                        }
                        if (TextUtils.isEmpty(salePrice)) {
                            UIUtils.showToastSafe("请填写放盘价");
                            return;
                        }

                        map = mHouseAdapter.getIsSelected();
                       /* for (Map.Entry<Integer, Boolean> entry : map.entrySet()) {
                           if(entry.getValue() == true){
                               int  position = entry.getKey();
                               HouseListBean houseListBean = list.get(position);
                               houseListBean.setRoomPrice(roomPrice);
                               list.set(position,houseListBean);
                           }
                        }*/
                       // mHouseAdapter.initDate();
                       // mHouseAdapter.notifyDataSetChanged();
                        upDataRoomPrice(roomCash,roomPrice,salePrice);
                        alertDialog.dismiss();
                        break;
                }
            }
        };
        alertDialog.findViewById(R.id.btn_cancel).setOnClickListener(listener);
        alertDialog.findViewById(R.id.bt_ok).setOnClickListener(listener);
        alertDialog.findViewById(R.id.ib_date).setOnClickListener(listener);
        alertDialog.findViewById(R.id.ib_choice).setOnClickListener(listener);

        mSubscription = RxBus.getInstance().toObserverable(CalendarBean.class)
                .subscribe(new Action1<CalendarBean>() {
                    @Override
                    public void call(CalendarBean bean) {
                        mPrice = bean.getPrice();
                        mStartDate = bean.getStartDate();
                        mEndDate = bean.getEndDate();
                        tvSalePrice.setText(mPrice);
                    }
                });
    }

    /**
     * 提交 修改价格
     * @param roomCash
     * @param roomPrice
     * @param salePrice
     */
    private void upDataRoomPrice(String roomCash, String roomPrice, String salePrice) {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        String str1 = mStartDate.replace("月","-");
        String mStartDate2 = String.valueOf(year) + "-" + str1.replace("日","");
        String str2 = mEndDate.replace("月","-");
        String mEndDate2 = String.valueOf(year) + "-"+ str2.replace("日","");
        HashMap<String, Object> map = new HashMap<>();
        map.put("skuIds",mNewDatas);
        map.put("roomBond", roomCash);
        map.put("startDate", mStartDate2);
        map.put("endDate", mEndDate2);
        map.put("listingPrice", salePrice);
        map.put("roomPrice", roomPrice);
        map.put("roomStatus", "1");
        String token = SPUtil.getString(HouseListActivity.this, Constants.TOKEN);
        String id = SPUtil.getString(HouseListActivity.this, Constants.ID);
        String autoSignStr = Constants.UPALLSKUPRICE.substring(Constants.UPALLSKUPRICE.lastIndexOf("0/") + 1) + "?token=";
        String signStr = UIUtils.Md5(autoSignStr + token);
        String url = Constants.UPALLSKUPRICE + "?token=" + id + "&&sign=" + signStr;
        HttpClient.post2(this, url, map, new CallBack<String>() {
            @Override
            public void onSuccess(String result) {
             //   UIUtils.showToastSafe(result);
                loadData();
            }
        });
    }


    private void showPopMenu() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_menu, null);
        //处理popWindow 显示内容
        handleLogic(contentView);
        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .create()
                .showAsDropDown(ibChoice, 0, 20);
    }

    private void handleLogic(View view) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCustomPopWindow != null) {
                    mCustomPopWindow.dissmiss();
                }
                String showContent = "";
                switch (v.getId()) {
                    case R.id.tv_online:
                        showContent = "已上线";
                        break;
                    case R.id.tv_care:
                        showContent = "维护中";
                        break;
                    case R.id.tv_sold:
                        showContent = "已下架";
                        break;
                }
                tvOnline.setText(showContent);
            }
        };
        view.findViewById(R.id.tv_online).setOnClickListener(listener);
        view.findViewById(R.id.tv_care).setOnClickListener(listener);
        view.findViewById(R.id.tv_sold).setOnClickListener(listener);
    }


    /**
     * 全选
     */
    private void selectedAll() {
        for (int i = 0; i < list.size(); i++) {
            mHouseAdapter.getIsSelected().put(i, flag);
        }
        mHouseAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (alertDialog != null && !alertDialog.isShowing()) {
            alertDialog = null;
        }
        if (mSubscription != null ) {
            if(!mSubscription.isUnsubscribed()){
                mSubscription.unsubscribe();
            }
        }
    }
}